package com.lst.servlet;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.LookReqPara;
import com.lst.entity.response.LookResPara;
import com.lst.model.ClientNum;
import com.lst.model.VideoInfo;
import com.lst.model.WenwInfo;
import com.lst.service.ClientNumService;
import com.lst.service.MstDiscussService;
import com.lst.service.VideoInfoService;
import com.lst.service.WenwInfoService;
import com.lst.utils.CommFunUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: LookListServlet
 * @Description: 发现功夫列表接口
 * @author zmm
 * @date 2017年9月23日 下午6:11:14
 *
 */
public class LookListServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID 
	 */
	private static final long serialVersionUID = 1L;

	private WenwInfoService wenwInfoService = ctx.getBean(WenwInfoService.class);

	private VideoInfoService videoInfoService = ctx.getBean(VideoInfoService.class);

	private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);

	private MstDiscussService mstDiscussService = ctx.getBean(MstDiscussService.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		LookResPara resPara = new  LookResPara();

		try {
			LookReqPara reqPara = getReqPara(request);

			if(isCheckField(reqPara,resPara)){
				Integer looktype = Integer.valueOf(reqPara.getLooktype());
				//String  searchwork = reqPara.getSearchwork();
				Integer page = Integer.valueOf(reqPara.getPage());
				Integer pagesize = Integer.valueOf(reqPara.getPagesize());
				String clientid = reqPara.getUserid();

				Map<String, Object> lookMap = new HashMap<String, Object>();

				lookMap.put("enabled", true);
				lookMap.put("isDeleted", false);				

				PageBounds pageBounds = new PageBounds(page,pagesize);

				if(CommCode.SYSTEM_CARESEL_RANGE_WENW.equals(looktype)){//发现文章

					lookMap.put("orderByClause", "wi.updatedate desc");

					List<WenwInfo> wenws = wenwInfoService.queryByList(lookMap, pageBounds);
					for(WenwInfo wi: wenws){

						//收藏量
						Integer favoritenum = CommFunUtils.opNum(null, wi.getId(), CommCode.SYSTEM_CARESEL_RANGE_WENW, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
						//分享量
						Integer sharenum = CommFunUtils.opNum(null, wi.getId(), CommCode.SYSTEM_CARESEL_RANGE_WENW, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
						//浏览量
						lookMap.clear();
						lookMap.put("enabled", true);
						lookMap.put("isDeleted", false);	
						lookMap.put("numtype", CommCode.SYSTEM_COUNT_BROWSE);
						lookMap.put("actid", wi.getId());
						lookMap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_WENW);

						List<ClientNum> browselist = clientNumService.queryByList(lookMap);

						Integer browsenum = 0;

						for(ClientNum c : browselist){
							browsenum += c.getNum() == null ? 0 : c.getNum();
						}

						wi.setFavoritenum(favoritenum);
						wi.setSharenum(sharenum);
						wi.setBrowsenum(browsenum);
						
						//评论量
						Map<String, Object> wenmap = new HashMap<String, Object>();

						wenmap.put("enabled", true);
						wenmap.put("iseleted", false);
						wenmap.put("tarid", wi.getId());
						wenmap.put("type", CommCode.SYSTEM_CARESEL_RANGE_WENW);

						Integer wendiscussnum = mstDiscussService.queryCountByMap(wenmap);

						wi.setReserved2(wendiscussnum);
						
						List<ClientNum> cns = null;
						if(!StringUtils.isEmpty(clientid)){
							Map<String, Object> cnmap = new HashMap<String, Object>();

							cnmap.put("enabled", true);
							cnmap.put("isDeleted", false);
							cnmap.put("clientid", Integer.valueOf(clientid));
							cnmap.put("numtype",CommCode.SYSTEM_COUNT_FAVORITE);
							cnmap.put("actid", wi.getId());
							cnmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_WENW);

							cns = clientNumService.queryByList(cnmap);
						}
						if(null==cns||cns.size()==0){
							wi.setIsFavorite(false);
						}else{
							wi.setIsFavorite(true);
						}
					}
					resPara.setWenws(wenws);
				} else{ //发现视频

					lookMap.put("orderByClause", "vi.updatedate desc");

					List<VideoInfo> vis = videoInfoService.queryByList(lookMap, pageBounds);

					for(VideoInfo vi: vis){
						String videotime = DateUtil.getFormatTime(vi.getCreatedate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
						vi.setVideotime(videotime);	

						//收藏量
						Integer favoritenum = CommFunUtils.opNum(null, vi.getId(), CommCode.SYSTEM_CARESEL_RANGE_VIDEO, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
						//分享量
						Integer sharenum = CommFunUtils.opNum(null, vi.getId(), CommCode.SYSTEM_CARESEL_RANGE_VIDEO, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
						//浏览量
						lookMap.clear();
						lookMap.put("enabled", true);
						lookMap.put("isDeleted", false);	
						lookMap.put("numtype", CommCode.SYSTEM_COUNT_BROWSE);
						lookMap.put("actid", vi.getId());
						lookMap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_VIDEO);

						List<ClientNum> browselist = clientNumService.queryByList(lookMap);

						Integer browsenum = 0;

						for(ClientNum c : browselist){
							browsenum += c.getNum() == null ? 0 : c.getNum();
						}

						vi.setFavoritenum(favoritenum);
						vi.setSharenum(sharenum);
						vi.setBrowsenum(browsenum);

						//评论量
						Map<String, Object> videomap = new HashMap<String, Object>();

						videomap.put("enabled", true);
						videomap.put("iseleted", false);
						videomap.put("tarid", vi.getId());
						videomap.put("type", CommCode.SYSTEM_CARESEL_RANGE_VIDEO);

						Integer videodiscussnum = mstDiscussService.queryCountByMap(videomap);

						vi.setVideodiscussnum(videodiscussnum);;

						List<ClientNum> cns = null;
						if(!StringUtils.isEmpty(clientid)){
							Map<String, Object> cnmap = new HashMap<String, Object>();

							cnmap.put("enabled", true);
							cnmap.put("isDeleted", false);
							cnmap.put("clientid", Integer.valueOf(clientid));							
							cnmap.put("numtype",CommCode.SYSTEM_COUNT_FAVORITE);	
							cnmap.put("actid", vi.getId());
							cnmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_VIDEO);

							cns = clientNumService.queryByList(cnmap);
						}
						if(null==cns||cns.size()==0){									
							vi.setIsFavorite(false);
						}else{
							vi.setIsFavorite(true);

						}
					}
					resPara.setVis(vis);
				}
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);
			}

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
//			logger.info(jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

//			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public LookReqPara getReqPara(HttpServletRequest request) {

		LookReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new LookReqPara());

			reqPara = (LookReqPara) baseRequest.clone();

			String looktype = request.getParameter("looktype");
			//String searchwork = request.getParameter("searchwork");
			String page = request.getParameter("page");
			String pagesize = request.getParameter("pagesize");
			String userid = request.getParameter("userid");

		//	logger.info("reqPara looktype: " + looktype);
		//	logger.info("reqPara searchwork: " + searchwork);
//			logger.info("reqPara page: " + page);
//			logger.info("reqPara pagesize: " + pagesize);
//			logger.info("reqPara userid: " + userid);

			reqPara.setLooktype(looktype);;
		//	reqPara.setSearchwork(searchwork);
			reqPara.setPage(page);
			reqPara.setPagesize(pagesize);
			reqPara.setUserid(userid);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		LookReqPara lookReqPara = (LookReqPara) reqPara;
		LookResPara lookResPara = (LookResPara) resPara;

		if (StringUtils.isEmpty(lookReqPara.getLooktype())) {
			lookResPara.setCode(CommCode.M_A000000);
			lookResPara.setMessage(CommCode.M_L000001);
		} else if(StringUtils.isEmpty(lookReqPara.getPage())){
			lookResPara.setCode(CommCode.M_A000000);
			lookResPara.setMessage(CommCode.M_P000009);
		} else if(StringUtils.isEmpty(lookReqPara.getPagesize())){
			lookResPara.setCode(CommCode.M_A000000);
			lookResPara.setMessage(CommCode.M_P000010);
		} else{
			flag = true;
		}

		return  flag;
	}
}
